<template>
  <view class="container">
    <!-- 顶部Tab -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="currentTab === 0 ? 'active' : ''"
        @tap="switchTab(0)"
      >
        <text class="tab-title">待审核</text>
        <text class="badge" v-if="pendingCount > 0">{{ pendingCount }}</text>
      </view>
      <view 
        class="tab-item" 
        :class="currentTab === 1 ? 'active' : ''"
        @tap="switchTab(1)"
      >
        <text class="tab-title">已处理</text>
      </view>
    </view>

    <!-- 待审核列表 -->
    <scroll-view 
      v-if="currentTab === 0" 
      class="scroll-container"
      scroll-y
      @scrolltolower="loadMorePending"
    >
      <view class="list">
        <!-- 空状态 -->
        <view v-if="pendingOrders.length === 0 && !isLoading" class="empty">
          <text class="empty-icon">📋</text>
          <text class="empty-text">暂无待审核退款</text>
        </view>

        <!-- 列表项 -->
        <view 
          v-for="(item, idx) in pendingOrders" 
          :key="idx"
          class="order-card"
          @tap="goDetail(item.id)"
        >
          <!-- 头部 -->
          <view class="card-header">
            <text class="order-number">{{ item.orderNo }}</text>
            <view class="status-tag pending">
              <text>待审核</text>
            </view>
          </view>

          <!-- 订单类型 -->
          <view class="card-row">
            <text class="label">订单类型</text>
            <text class="value">{{ getTypeText(item.orderType) }}</text>
          </view>

          <!-- 金额 -->
          <view class="card-row">
            <text class="label">订单金额</text>
            <text class="value price">¥{{ item.actualAmount }}</text>
          </view>

          <!-- 申请时间 -->
          <view class="card-row">
            <text class="label">申请时间</text>
            <text class="value">{{ formatDate(item.refundApplyTime) }}</text>
          </view>

          <!-- 用户信息 -->
          <view class="card-row">
            <text class="label">用户信息</text>
            <text class="value small">{{ item.deliveryAddress || '未知' }}</text>
          </view>

          <!-- 操作按钮 -->
          <view class="card-actions">
            <view class="btn-reject" @tap.stop="handleReject(item)">
              <text>拒绝</text>
            </view>
            <view class="btn-approve" @tap.stop="handleApprove(item)">
              <text>同意</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="isLoading" class="loading-box">
        <text>加载中...</text>
      </view>
      <view v-if="!hasMorePending && pendingOrders.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>

    <!-- 已处理列表 -->
    <scroll-view 
      v-if="currentTab === 1" 
      class="scroll-container"
      scroll-y
      @scrolltolower="loadMoreProcessed"
    >
      <view class="list">
        <!-- 空状态 -->
        <view v-if="processedOrders.length === 0 && !isLoading" class="empty">
          <text class="empty-icon">📋</text>
          <text class="empty-text">暂无已处理退款</text>
        </view>

        <!-- 列表项 -->
        <view 
          v-for="(item, idx) in processedOrders" 
          :key="idx"
          class="order-card"
          @tap="goDetail(item.id)"
        >
          <!-- 头部 -->
          <view class="card-header">
            <text class="order-number">{{ item.orderNo }}</text>
            <view :class="'status-tag ' + getStatusClass(item.refundStatus)">
              <text>{{ getStatusText(item.refundStatus) }}</text>
            </view>
          </view>

          <!-- 订单类型 -->
          <view class="card-row">
            <text class="label">订单类型</text>
            <text class="value">{{ getTypeText(item.orderType) }}</text>
          </view>

          <!-- 金额 -->
          <view class="card-row">
            <text class="label">订单金额</text>
            <text class="value price">¥{{ item.actualAmount }}</text>
          </view>

          <!-- 退款金额 -->
          <view class="card-row" v-if="item.refundAmount">
            <text class="label">退款金额</text>
            <text class="value price highlight">¥{{ item.refundAmount }}</text>
          </view>

          <!-- 处理时间 -->
          <view class="card-row">
            <text class="label">处理时间</text>
            <text class="value">{{ formatDate(item.updateTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="isLoading" class="loading-box">
        <text>加载中...</text>
      </view>
      <view v-if="!hasMoreProcessed && processedOrders.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getPendingRefunds, getProcessedRefunds } from '@/api/refund'
import { getOrderTypeText } from '@/utils/orderStatus'

export default {
  data() {
    return {
      currentTab: 0,
      pendingOrders: [],
      processedOrders: [],
      pendingCount: 0,
      isLoading: false,
      pendingPage: 1,
      processedPage: 1,
      pageSize: 10,
      hasMorePending: true,
      hasMoreProcessed: true
    }
  },
  onLoad() {
    this.loadPendingData()
  },
  onShow() {
    // 刷新当前tab数据
    if (this.currentTab === 0) {
      this.refreshPending()
    } else {
      this.refreshProcessed()
    }
  },
  onPullDownRefresh() {
    if (this.currentTab === 0) {
      this.refreshPending()
    } else {
      this.refreshProcessed()
    }
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  methods: {
    // 切换Tab
    switchTab(index) {
      if (this.currentTab === index) return
      this.currentTab = index
      
      if (index === 0 && this.pendingOrders.length === 0) {
        this.loadPendingData()
      } else if (index === 1 && this.processedOrders.length === 0) {
        this.loadProcessedData()
      }
    },

    // 加载待审核数据
    async loadPendingData() {
      if (this.isLoading || !this.hasMorePending) return
      
      this.isLoading = true
      
      try {
        const res = await getPendingRefunds(this.pendingPage, this.pageSize)
        //console.log('待审核数据:', res)
        
        // 简单粗暴：直接取数据，转成纯对象
        let list = []
        if (res && res.records && Array.isArray(res.records)) {
          list = JSON.parse(JSON.stringify(res.records))
        }
        
        // 追加到列表
        this.pendingOrders = [...this.pendingOrders, ...list]
        
        // 更新计数
        if (res.total) {
          this.pendingCount = parseInt(res.total)
        }
        
        // 判断是否还有更多
        if (res.pages) {
          this.hasMorePending = this.pendingPage < parseInt(res.pages)
        } else {
          this.hasMorePending = list.length >= this.pageSize
        }
        
        //console.log('当前待审核列表长度:', this.pendingOrders.length)
        
      } catch (err) {
        console.error('加载失败:', err)
        uni.showToast({
          title: err.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },

    // 加载已处理数据
    async loadProcessedData() {
      if (this.isLoading || !this.hasMoreProcessed) return
      
      this.isLoading = true
      
      try {
        const res = await getProcessedRefunds(this.processedPage, this.pageSize)
        //console.log('已处理数据:', res)
        
        let list = []
        if (res && res.records && Array.isArray(res.records)) {
          list = JSON.parse(JSON.stringify(res.records))
        }
        
        this.processedOrders = [...this.processedOrders, ...list]
        
        if (res.pages) {
          this.hasMoreProcessed = this.processedPage < parseInt(res.pages)
        } else {
          this.hasMoreProcessed = list.length >= this.pageSize
        }
        
        //console.log('当前已处理列表长度:', this.processedOrders.length)
        
      } catch (err) {
        console.error('加载失败:', err)
        uni.showToast({
          title: err.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },

    // 加载更多 - 待审核
    loadMorePending() {
      if (!this.hasMorePending || this.isLoading) return
      this.pendingPage++
      this.loadPendingData()
    },

    // 加载更多 - 已处理
    loadMoreProcessed() {
      if (!this.hasMoreProcessed || this.isLoading) return
      this.processedPage++
      this.loadProcessedData()
    },

    // 刷新待审核
    refreshPending() {
      this.pendingPage = 1
      this.pendingOrders = []
      this.hasMorePending = true
      this.loadPendingData()
    },

    // 刷新已处理
    refreshProcessed() {
      this.processedPage = 1
      this.processedOrders = []
      this.hasMoreProcessed = true
      this.loadProcessedData()
    },

    // 跳转详情
    goDetail(orderId) {
      uni.navigateTo({
        url: `/pages/merchant/refund-detail?orderId=${orderId}`
      })
    },

    // 拒绝
    handleReject(item) {
      uni.showModal({
        title: '拒绝退款',
        content: '确定要拒绝这个退款申请吗？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: `/pages/merchant/refund-detail?orderId=${item.id}&action=reject`
            })
          }
        }
      })
    },

    // 同意
    handleApprove(item) {
      uni.navigateTo({
        url: `/pages/merchant/refund-detail?orderId=${item.id}&action=approve`
      })
    },

    // 格式化时间
    formatDate(timeStr) {
      if (!timeStr) return '-'
      const d = new Date(timeStr)
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hour = String(d.getHours()).padStart(2, '0')
      const minute = String(d.getMinutes()).padStart(2, '0')
      return `${month}-${day} ${hour}:${minute}`
    },

    // 订单类型文本
    getTypeText(type) {
      return getOrderTypeText(type) || '未知'
    },

    // 退款状态文本
    getStatusText(status) {
      const map = {
        1: '审核中',
        2: '已同意',
        3: '已拒绝'
      }
      return map[status] || '未知'
    },

    // 退款状态样式
    getStatusClass(status) {
      const map = {
        1: 'pending',
        2: 'approved',
        3: 'rejected'
      }
      return map[status] || 'pending'
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

/* Tab栏 */
.tabs {
  display: flex;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.tab-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .tab-title {
    font-size: 30rpx;
    color: #666;
  }
  
  .badge {
    position: absolute;
    top: 12rpx;
    right: 60rpx;
    min-width: 32rpx;
    height: 32rpx;
    line-height: 32rpx;
    text-align: center;
    background: #ff4d4f;
    color: #fff;
    font-size: 20rpx;
    border-radius: 16rpx;
    padding: 0 6rpx;
  }
  
  &.active {
    .tab-title {
      color: #ff6b35;
      font-weight: bold;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background: #ff6b35;
      border-radius: 2rpx;
    }
  }
}

/* 滚动容器 */
.scroll-container {
  flex: 1;
  height: 0;
}

.list {
  padding: 24rpx;
}

/* 订单卡片 */
.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.order-number {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.status-tag {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  
  &.pending {
    background: #fff7e6;
    color: #fa8c16;
  }
  
  &.approved {
    background: #f6ffed;
    color: #52c41a;
  }
  
  &.rejected {
    background: #fff1f0;
    color: #ff4d4f;
  }
}

.card-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  
  .label {
    font-size: 26rpx;
    color: #999;
  }
  
  .value {
    font-size: 26rpx;
    color: #333;
    
    &.price {
      color: #ff6b35;
      font-weight: bold;
    }
    
    &.highlight {
      color: #52c41a;
    }
    
    &.small {
      font-size: 24rpx;
      color: #666;
      max-width: 400rpx;
      text-align: right;
    }
  }
}

.card-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 24rpx;
  padding-top: 20rpx;
  border-top: 1px solid #f0f0f0;
}

.btn-reject,
.btn-approve {
  flex: 1;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-reject {
  background: #f5f5f5;
  color: #666;
}

.btn-approve {
  background: #ff6b35;
  color: #fff;
}

/* 空状态 */
.empty {
  text-align: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 100rpx;
  display: block;
  margin-bottom: 20rpx;
  opacity: 0.3;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-box,
.no-more {
  text-align: center;
  padding: 40rpx 0;
  font-size: 26rpx;
  color: #999;
}
</style>